package dao;

import application.exceptions.ItemNotFoundException;
import mappings.Phases;
import mappings.Producent;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import utils.HibernateUtil;

import java.util.List;

@SuppressWarnings("JpaQlInspection")
public class PhaseDao
{
    private static SessionFactory sessionFactory = HibernateUtil.getSessionFactory();

    public List<Phases> getAllPhases()
    {
        Session session = sessionFactory.openSession();

        List<Phases> phases = session.createCriteria(Phases.class)
                .list();

        session.close();

        return phases;
    }

    public Phases addPhase(String name)
    {
        Phases phase = new Phases();
        phase.setName(name);

        org.hibernate.classic.Session session = sessionFactory.openSession();
        Transaction tx = session.beginTransaction();

        session.save(phase);

        tx.commit();
        session.close();

        return phase;
    }

    public Phases editPhase(Integer id, Phases phase) throws ItemNotFoundException
    {
        org.hibernate.classic.Session session = sessionFactory.openSession();
        Transaction tx = session.beginTransaction();

        Phases phaseToEdit = (Phases) session.get(Phases.class, id);

        if(phaseToEdit == null)
        {
            tx.rollback();
            session.close();
            throw new ItemNotFoundException();
        }

        phaseToEdit.setName(phase.getName());
        session.update(phaseToEdit);
        tx.commit();
        session.close();

        return phaseToEdit;
    }

    public void deletePhase(Integer id) throws ItemNotFoundException
    {
        org.hibernate.classic.Session session = sessionFactory.openSession();
        Transaction tx = session.beginTransaction();

        int affectedRows = session.createQuery("delete Phases where id = :id")
                .setParameter("id", id)
                .executeUpdate();

        if(affectedRows == 0)
        {
            tx.rollback();
            session.close();
            throw new ItemNotFoundException();
        }

        tx.commit();
        session.close();
    }
}
